package com.longqinuo.mycarservice.fragments;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.longqinuo.mycarservice.R;
import com.longqinuo.mycarservice.utils.BreakResultAdapter;
import com.longqinuo.mycarservice.utils.PathUtils;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link BreakResultFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BreakResultFragment extends Fragment implements View.OnClickListener {

    private ListView mListView;

    private ImageView mBack;
    private FragmentManager manager;
    private List<Map<String, String>> mList;
    private BreakResultAdapter mAdapter;
    private String carNumber;  //车牌

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private RequestQueue queue;   //Volley请求队列
    private TextView tv_car_number;
    private TextView tv_car_type;
    private TextView tv_break_handle;
    private TextView tv_break_money;
    private TextView tv_break_time;
    private TextView tv_break_all_fen;
    private int allMoney;  //总罚款
    private int allGrade;    //总扣分

    public BreakResultFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BreakResultFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BreakResultFragment newInstance(String param1, String param2) {
        BreakResultFragment fragment = new BreakResultFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            carNumber = mParam1;
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        queue = Volley.newRequestQueue(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_break_result, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        manager = getActivity().getSupportFragmentManager();
        mListView = (ListView) view.findViewById(R.id.lv_query_result);
        mBack = (ImageView) view.findViewById(R.id.iv_back_break_query);
        mBack.setOnClickListener(this);
        initData();
        tv_car_number = (TextView) view.findViewById(R.id.tv_car_number); //车牌号
        tv_car_number.setText(carNumber);
        tv_car_type = (TextView) view.findViewById(R.id.tv_car_type);  //车系

        tv_break_handle = (TextView) view.findViewById(R.id.tv_break_handle);  //违章未处理

        tv_break_money = (TextView) view.findViewById(R.id.tv_break_money);  //总罚款
        tv_break_time = (TextView) view.findViewById(R.id.tv_break_time);  //违章次数
        tv_break_all_fen = (TextView) view.findViewById(R.id.tv_break_all_fen);  //总扣分
    }

    private void initData() {
        mList = new ArrayList<>();
        mAdapter = new BreakResultAdapter(getActivity(), mList);
        mListView.setAdapter(mAdapter);
        breakQuery();   //执行 违章查询请求
    }

    private void breakQuery() {
        String url = PathUtils.BREAK_QUERY + "?city=SH&hphm=%E8%8B%8FL50A11" + "&engineno=123456&key=" + PathUtils.JUHE_APP_KEY;
        Log.d("请求URL", "请求" + url);
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.d("请求s", "请求" + s);
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    String resultcode = jsonObject.getString("resultcode");
                    String reason = jsonObject.getString("reason");
                    Toast.makeText(getActivity(), reason, Toast.LENGTH_SHORT).show();
                    if (resultcode.equals("200")) {
                        JSONObject result = jsonObject.getJSONObject("result");
                        JSONArray array = result.getJSONArray("lists");
                        int len = array.length();
                        tv_break_time.setText(len+"");
                        for (int i = 0; i < len; i++) {
                            Map<String, String> map = new HashMap<>();
                            JSONObject o = array.getJSONObject(i);
                            String date = o.getString("date");
                            String area = o.getString("area");
                            String act = o.getString("act");
                            String money = o.getString("money");
                            int fine = Integer.valueOf(money);
                            allMoney += fine;
                            String fen = o.getString("fen");
                            int grade = Integer.valueOf(fen);
                            allGrade += grade;
                            map.put("time", date);
                            map.put("place", area);
                            map.put("behavior", act);
                            map.put("fine", money);
                            map.put("grade", fen);
                            mList.add(map);
                        }
                        tv_break_money.setText(allMoney+"");  //罚款
                        tv_break_all_fen.setText(allGrade+"");  //扣分
                        mAdapter.notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        queue.add(request);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back_break_query:
                manager.popBackStack();
                break;
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
